﻿using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using Microsoft.Win32;
using HongShijin.PrintActiveX;
using System.EnterpriseServices.Internal;

namespace HongShijin.PrintActiveX.Studio
{
	static class Common
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			//string t;
			//XmlDocument xml = new XmlDocument();
			//t = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\a.xsl");
			//xml.LoadXml(t);
			//XslCompiledTransform xsl = new XslCompiledTransform();
			//xsl.Load(xml);
			//t = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\a.xml");
			//xml.LoadXml(t);
			//StringWriter sw = new StringWriter();
			//xsl.Transform(xml, new XmlTextWriter(sw));
			//MessageBox.Show(sw.ToString());

			if (args == null || args.Length == 0)
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new FormXml());
				return;
			}

			for (int i = 0; i < args.Length; i++)
			{
				if (args[i].ToLower() == "/regasm" && args.Length > i + 1)
				{
					i++;
					Common.RegAsm(args[i]);
					continue;
				}

				if (args[i].ToLower() == "/trustedweb" && args.Length > i + 1)
				{
					i++;
					Common.TrustedWeb(args[i]);
					continue;
				}
			}
		}

		private static void RegAsm(string target)
		{
			//new Publish().GacInstall(target);
			//new Publish().RegisterAssembly(target);
			Process process = new Process();
			process.StartInfo.FileName = Path.GetDirectoryName(typeof(File).Assembly.Location) + @"\RegAsm.exe";
			string t = Path.GetDirectoryName(typeof(Common).Assembly.Location);
			t = Path.Combine(t, target);
			if (File.Exists(t))
				target = t;
			process.StartInfo.Arguments = @"/codebase """ + target + @"""";
			process.StartInfo.RedirectStandardOutput = true;
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.CreateNoWindow = true;
			process.Start();
			t = @"""" + process.StartInfo.FileName + @""" " + process.StartInfo.Arguments;
			File.WriteAllText(Path.ChangeExtension(typeof(PrintMechanically).Assembly.Location, "bat"), t);
			t += t + "\r\n\r\n" + process.StandardOutput.ReadToEnd();
			File.WriteAllText(Path.ChangeExtension(typeof(PrintMechanically).Assembly.Location, "log"), t);

			process = new Process();
			process.StartInfo.FileName = Path.ChangeExtension(typeof(PrintMechanically).Assembly.Location, "bat");
			process.StartInfo.RedirectStandardOutput = true;
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.CreateNoWindow = true;
			process.Start();
			t = t + "\r\n\r\n" + process.StandardOutput.ReadToEnd();
			File.AppendAllText(Path.ChangeExtension(typeof(PrintMechanically).Assembly.Location, "log"), t);

			//Process process = new Process();
			//process.StartInfo.FileName = Path.ChangeExtension(typeof(PrintMechanically).Assembly.Location, "bat");
			//string t = Path.GetDirectoryName(typeof(Common).Assembly.Location);
			//t = Path.Combine(t, target);
			//if (File.Exists(t))
			//    target = t;
			//process.StartInfo.Arguments = Path.GetDirectoryName(typeof(File).Assembly.Location) + @"\RegAsm.exe /codebase " + target;
			//process.StartInfo.RedirectStandardOutput = true;
			//process.StartInfo.UseShellExecute = false;
			//process.StartInfo.CreateNoWindow = true;
			//process.Start();
			//File.WriteAllText("C:\\regasm.log", process.StandardOutput.ReadToEnd());
		}

		private static void TrustedWeb(string target)
		{
			const int LEVEL = 2;

			string t;
			object o;
			string[] ts;
			IPAddress ip;
			RegistryKey reg;
			RegistryKey root = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap");
			string prefix = "http";
			int i = target.IndexOf("://");
			if (i > 0)
			{
				prefix = target.Substring(0, i);
				target = target.Substring(i + 3);
			}

			#region IP

			if (IPAddress.TryParse(target, out ip))
			{
				root = root.OpenSubKey("Ranges", true);
				ts = root.GetSubKeyNames();
				for (i = 0; i < ts.Length; i++)
				{
					reg = root.OpenSubKey(ts[i], true);
					o = reg.GetValue(":Range");
					if (o == null || o.ToString() != target)
						continue;

					reg.SetValue(prefix, LEVEL, RegistryValueKind.DWord);
					reg.Close();
					return;
				}
				t = null;
				for (i = 1; i < ts.Length + 1; i++)
				{
					if (ts[i - 1] != "Range" + i)
					{
						t = "Range" + i;
						break;
					}
				}
				if (string.IsNullOrEmpty(t))
					t = "Range" + i;
				root = root.CreateSubKey(t);
				root.SetValue(prefix, LEVEL, RegistryValueKind.DWord);
				root.SetValue(":Range", target, RegistryValueKind.String);
				root.Close();
				return;
			}

			#endregion

			#region Domain

			t = string.Empty;
			if (target[0] == '*')
				Process.Start(prefix + "://" + target.Substring(2));
			else
				Process.Start(prefix + "://" + target);
			ts = target.Split('.');
			for (i = ts.Length - 1; i >= 0; i--)
			{
				if (ts.Length > i + 1)
					t = '.' + t;
				t = ts[i] + t;
				if (ts[i].Length > 2)
					break;
			}
			if (t.IndexOf('.') < 0 && ts.Length > 1)
			{
				if (ts.Length > 2)
					t = ts[1] + '.' + t;
				else
					t = ts[0] + '.' + t;
			}
			root = root.OpenSubKey("Domains", true);
			reg = root.OpenSubKey(t, true);
			if (reg == null)
				reg = root.CreateSubKey(t);
			if (target == t)
			{
				reg.SetValue(prefix, LEVEL, RegistryValueKind.DWord);
				reg.Close();
				root.Close();
				return;
			}

			t = target.Substring(0, target.Length - t.Length - 1);
			if (t == "*")
			{
				reg.SetValue(prefix, LEVEL, RegistryValueKind.DWord);
				reg.Close();
				root.Close();
				return;
			}

			root = reg;
			reg = root.OpenSubKey(t, true);
			if (reg == null)
				reg = root.CreateSubKey(t);
			reg.SetValue(prefix, LEVEL, RegistryValueKind.DWord);
			reg.Close();
			root.Close();

			#endregion
		}

		public static string GetFile(string name)
		{
			string t;
			t = GetFile(Assembly.GetEntryAssembly().Location, name);
			if(!string.IsNullOrEmpty(t))
				return t;

			t = GetFile(Assembly.GetExecutingAssembly().Location, name);
			if(!string.IsNullOrEmpty(t))
				return t;

			t = GetFile(Assembly.GetCallingAssembly().Location, name);
			if(!string.IsNullOrEmpty(t))
				return t;

			return null;
		}

		public static string GetFile(string path, string name)
		{
			DirectoryInfo dir = new DirectoryInfo(path);
			while (dir.FullName != dir.Root.FullName)
			{
				path = Path.Combine(dir.FullName, name);
				if (File.Exists(path))
					return path;

				dir = dir.Parent;
			}
			return null;
		}
	}

	//[System.Runtime.InteropServices.Guid("2d8f6cda-307f-43ff-ad19-3d7128f4f79f")]
	//public class CLSID : Form
	//{
	//}
}